package edu.chl.dat076.datesite.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Christoffer
 */

@WebFilter
public class AuthFilter implements Filter {
	List<String> okUrl = new ArrayList<String>();
    
    public AuthFilter() {    
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// Kolla om någon är inloggad
		if (req.getSession().getAttribute("user") == null) {
			
			// Kolla om den reuestade URLen är ok att gå till utan att vara inloggad
			if (URLProcessor.letPassThrough(req.getRequestURI(), okUrl)) {
				chain.doFilter(request, response);
			} else {
				res.sendRedirect("/datesite/loginregister.jsf");
			}
		} else {
			chain.doFilter(request, response);
		}
    }

    @Override
    public void destroy() {        
    }

    @Override
    public void init(FilterConfig filterConfig) {        
		okUrl.add("/datesite/loginregister.jsf");
		okUrl.add("/datesite/javax.faces.resource/styles.css.jsf");
		okUrl.add("/datesite/javax.faces.resource/jsf.js.jsf");
		okUrl.add("/datesite/javax.faces.resource/themes/sam/theme.css.jsf");
		okUrl.add("/datesite/javax.faces.resource/messages/messages.css.jsf");
    }
}